package com.zztl.infiniteBand.ui.activity


import android.app.Activity
import android.content.Intent
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import butterknife.OnClick
import com.zztl.infiniteBand.BraceletApplication
import com.zztl.infiniteBand.R
import com.zztl.infiniteBand.base.BaseMvpActivity
import com.zztl.infiniteBand.dao.BindedWatchBean
import com.zztl.infiniteBand.model.BindedDeviceBean
import com.zztl.infiniteBand.model.LoginBean
import com.zztl.infiniteBand.net.RetorfitServiceManger
import com.zztl.infiniteBand.net.requestBean.LoginRequest
import com.zztl.infiniteBand.presenter.LoginPresenter
import com.zztl.infiniteBand.storage.BillPreference
import com.zztl.infiniteBand.storage.Constans
import com.zztl.infiniteBand.storage.PreferenceKeys
import com.zztl.infiniteBand.ui.view.CommonItemView2
import com.zztl.infiniteBand.ui.view.mvpview.LoginView
import com.zztl.infiniteBand.util.toast
import kotlinx.android.synthetic.main.activity_login.*

class LoginActivity : BaseMvpActivity<LoginView, LoginPresenter>(), LoginView {


    lateinit var mLoginPresenter: LoginPresenter

    override fun setLayoutId() = R.layout.activity_login
    var isLook: Boolean = false

    override fun initBase() {
        itemPwd.setRightImg(R.mipmap.biyanjing)

        itemPwd.setItemRightClickListener(object : CommonItemView2.OnItemRightClickListener {
            override fun onClickItemRight(viewID: Int) {
                isLook = !isLook.apply {
                    if (this) {
                        itemPwd.middleEdit.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
                        itemPwd.setRightImg(R.mipmap.biyanjing)
                    } else {
                        itemPwd.middleEdit.inputType = InputType.TYPE_CLASS_TEXT
                        itemPwd.setRightImg(R.mipmap.zhengyanjing)
                    }
                }
            }
        })
        itemPhone.middleEdit.addTextChangedListener(Watcher(itemPhone.middleEdit))
        itemPwd.middleEdit.addTextChangedListener(Watcher(itemPwd.middleEdit))
        itemPhone.leftImgTv.apply {

            setOnClickListener(object : View.OnClickListener {
                override fun onClick(v: View?) {
                    val intent = Intent(this@LoginActivity, CountryCodeActivity::class.java)
                    showActivityForResult(intent, Constans.COUNTRY_CODE)
                }

            })
        }
    }

    override fun onResume() {
        val phoneNum = BillPreference.getApp(PreferenceKeys.DEFAULT_PHONE.name, "") as String
        itemPhone.setMiddleEditTextStr(phoneNum)
        itemPhone.leftImgTv.text = "+${BillPreference.getApp(PreferenceKeys.COUNTYRCODE.name, "86") as String}"
        super.onResume()
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        data?.let {
            if (Constans.COUNTRY_CODE == requestCode && resultCode == Activity.RESULT_OK) {
                itemPhone.leftImgTv.text = "+${data.getStringExtra(Constans.COUNTRY_CODE_STR)}"
            }
        }
    }

    override fun createPresenter(): LoginPresenter {
        mLoginPresenter = LoginPresenter()
        return mLoginPresenter

    }

    inner class Watcher(edit: EditText) : TextWatcher {
        private val editText by lazy {
            edit
        }

        override fun afterTextChanged(s: Editable?) {
            s?.let {
                btnLogin.isEnabled = itemPhone.middleEditStr.isNotEmpty() && itemPwd.middleEditStr.length >= 6
            }

        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }
    }

    @OnClick(R.id.btnRegister, R.id.btnLogin, R.id.btnForgetPwd)
    fun click(v: View) {
        when (v.id) {
            R.id.btnRegister -> showActivity(this, RegisterActivity::class.java)
            R.id.btnLogin -> if (mLoginPresenter.check(itemPhone.middleEditStr, itemPwd.middleEditStr)) {
                mLoginPresenter.login(LoginRequest(itemPhone.middleEditStr, itemPwd.middleEditStr, itemPhone.leftImgTv.text.toString()), this)
            }
            R.id.btnForgetPwd -> {
                val intent = Intent(this, ForgetOrResetPwdActivity::class.java)
                intent.putExtra(Constans.ACTIVITY_FROM, "login")
                showActivity(intent)
            }
        }
    }

    override fun loginSuccess(loginBean: LoginBean) {
        BillPreference.putApp(PreferenceKeys.TOKEN.name, loginBean.data!!.token!!)
        BillPreference.putApp(PreferenceKeys.DEFAULT_PHONE.name, loginBean.data!!.email!!)
        BillPreference.putApp(PreferenceKeys.LOGINED.name, true)
        BillPreference.putApp(PreferenceKeys.SMSTOGGLE.name, false)
//        BillPreference.putApp(PreferenceKeys.COUNTYRCODE.name, "86")
        //        showActivity(this, MainActivity.class);
        RetorfitServiceManger.reSetRetroServiceManager()
        mLoginPresenter.getBindDevice(this)
    }

    override fun loginFail() {

    }

    override fun getBindDeviceList(bean: BindedDeviceBean) {
        BraceletApplication.getmDaoSession()?.bindedWatchBeanDao?.let {
            it.deleteAll()
            it.insertOrReplaceInTx(bean.data?.rows?.filter { rowsBean -> rowsBean.mac!!.isNotEmpty() }?.flatMap { rowBean ->
                listOf(
                        BindedWatchBean().apply {
                            bluetoothId = rowBean.bluetoothId
                            imei = rowBean.imei
                            mac = rowBean.mac
                            name = rowBean.name
                            type = rowBean.type
                        }
                )
            })
        }
        skipActivity(this, MainActivity::class.java)
    }

    override fun getBindDeviceListFail() {
        toast(getString(R.string.登录失败稍后再试))
    }

    override fun onDestroy() {
        super.onDestroy()
    }

}
